import json

import cv2
import numpy as np
import scipy
import scipy.misc
import scipy.ndimage
import scipy.signal
import logging
import os.path
from logging import debug, info, error, warning
import math
import shutil

import pbcvt

TMP_OUT = 'static/diag_result/'
if not os.path.exists(TMP_OUT):
    os.mkdir(TMP_OUT)
FORMAT = '[%(levelname)-5s]%(asctime)-8s %(filename)s:%(lineno)d %(message)s'
DATEFORMAT = '%H:%M:%S'
logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATEFORMAT)
logging.debug('start')

home_dir = os.getenv('HOME', '')
db_root = home_dir + '/data'
out_root = db_root + '/out'
flist_name = out_root + '/filelist'
lesion_root = home_dir + '/data/pixellevel/出血-红色'
original_root = home_dir + '/data/pixellevel/原始'

out_original_root = out_root + '/original'
out_lesion_root = out_root + '/ha'
out_mask_root = out_root + '/mask'
import cv2

for dir in [out_root, out_original_root, out_lesion_root,out_mask_root]:
    if not os.path.exists(dir):
        os.mkdir(dir)

lesion_list = os.listdir(lesion_root)
original_list = os.listdir(original_root)
debug(original_list)


def pre_pocess(img, label):
    # crop file
    left, right = 0, img.shape[1] - 1
    top, bottom = 0, img.shape[0] - 1

    while True:
        s = img[:, left, 1].sum() / img.shape[1]
        if s > 5:
            break
        left += 5
    while True:
        s = img[:, right, 1].sum() / img.shape[1]
        if s > 5:
            break
        right -= 5
    while True:
        s = img[top, :, 1].sum() / img.shape[0]
        if s > 5:
            break
        top += 5
    while True:
        s = img[bottom, :, 1].sum() / img.shape[0]
        if s > 5:
            break
        bottom -= 5
    img = img[top:bottom, left:right, :]
    label = label[top:bottom, left:right]
    mask = img[:, :, 0] > 10

    label = scipy.ndimage.binary_closing(label, np.ones((7, 7)), 5)
    mask = scipy.ndimage.binary_opening(mask, np.ones((7, 7)))

    # zoom_factor = [
    #     300 / img.shape[0],
    #     300 / img.shape[1],
    #     1
    # ]
    # zoomed_img = scipy.ndimage.zoom(img, zoom_factor, mode='nearest')
    # zoomed_label = scipy.ndimage.zoom(label, zoom_factor[:-1], mode='nearest')
    return img, label, mask


index = 0
list_file = open(flist_name, 'w')
pixel_sum = np.zeros(3)
pixel_count = 0

for lesion_img_name in lesion_list:
    original_name = lesion_img_name
    while original_name[0] in ['L', 'R', 'l', 'r']:
        original_name = original_name[1:]
    pos = original_name.find('-')
    if pos >= 0:
        original_name = original_name[:pos] + original_name[pos + 2:]
    aval = original_list.count(original_name) > 0
    debug(original_name + ' ' + str(aval))
    if aval:
        original_img = scipy.misc.imread(original_root + '/' + original_name)
        lesion_img = scipy.misc.imread(lesion_root + '/' + lesion_img_name)
        lesion_mask = lesion_img[:, :, 0] > 230
        lesion_mask *= lesion_img[:, :, 1] < 20

        original_img, lesion_mask, mask = pre_pocess(original_img, lesion_mask)
        # lesion_mask = scipy.ndimage.binary_dilation(lesion_mask, structure=np.ones((3, 3)))

        pixel_sum += original_img[mask].sum(0)
        pixel_count += mask.sum()

        info(pixel_sum/pixel_count)

        num_label, labels, stats, centroids = cv2.connectedComponentsWithStats(lesion_mask.astype(np.int8))
        for i in range(1, num_label):
            if stats[i][cv2.CC_STAT_AREA] < 10:
                continue

            top = stats[i][cv2.CC_STAT_TOP]
            bottom = top + stats[i][cv2.CC_STAT_HEIGHT]
            left = stats[i][cv2.CC_STAT_LEFT]
            right = stats[i][cv2.CC_STAT_LEFT] + stats[i][cv2.CC_STAT_WIDTH]

            pitch_lesion = lesion_mask[top:bottom, left:right]
            area = (pitch_lesion>0).sum()
            if area > (bottom - top) * (right - left) / 2:
                top = max(0,top - math.floor(stats[i][cv2.CC_STAT_HEIGHT] / 2))
                bottom = min(lesion_mask.shape[0]-1, bottom + math.floor(stats[i][cv2.CC_STAT_HEIGHT] / 2))
                left = max(0,left - math.floor(stats[i][cv2.CC_STAT_WIDTH] / 2))
                right = min(lesion_mask.shape[1]-1, right + math.floor(stats[i][cv2.CC_STAT_WIDTH] / 2))

            olname = out_lesion_root + '/%010d.jpg' % index
            scipy.misc.imsave(olname, lesion_mask[top:bottom, left:right])
            ooname = out_original_root + '/%010d.jpg' % index
            scipy.misc.imsave(ooname, original_img[top:bottom, left:right, :])
            omname = out_mask_root + '/%010d.jpg' % index
            scipy.misc.imsave(omname, mask[top:bottom, left:right])
            list_file.write('%s %s %s\n' % (ooname, olname, omname))
            index += 1
            debug(stats[i][cv2.CC_STAT_AREA])